using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 权限仓储实现
    /// 提供权限实体的数据访问功能实现（EF Core）
    /// </summary>
    public class PermissionRepository : IPermissionRepository
    {
        private readonly LowCodeDbContext _context;

        public PermissionRepository(LowCodeDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有权限
        /// </summary>
        public async Task<IEnumerable<Permission>> GetAllAsync()
        {
            return await _context.Permissions
                .AsNoTracking()
                .OrderBy(p => p.SortOrder)
                .ThenBy(p => p.Id)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取权限
        /// </summary>
        public async Task<Permission?> GetByIdAsync(long id)
        {
            return await _context.Permissions
                .AsNoTracking()
                .FirstOrDefaultAsync(p => p.Id == id);
        }

        /// <summary>
        /// 添加新的权限
        /// </summary>
        public async Task AddAsync(Permission entity)
        {
            await _context.Permissions.AddAsync(entity);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        public async Task UpdateAsync(Permission entity)
        {
            _context.Permissions.Update(entity);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        public async Task DeleteAsync(long id)
        {
            var entity = await _context.Permissions.FindAsync(id);
            if (entity != null)
            {
                _context.Permissions.Remove(entity);
                await _context.SaveChangesAsync();
            }
        }
    }
}
